﻿//=======================================================
// Author: Jonas Follesø <jonas@follesoe.no>
// Copyright (c) 2008
//
// Licensed under the Microsoft Public License (Ms-PL)
// A copy of the license is available at 
// http://www.opensource.org/licenses/ms-pl.html
//=======================================================

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.ComponentModel;
using System.Windows.Shapes;
using System.Windows.Media;

namespace Colorful.Control
{
    public partial class SearchPanel : UserControl
    {
        public static readonly RoutedEvent StartProgressEvent = EventManager.RegisterRoutedEvent("StartProgress", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(SearchPanel));
        public static readonly RoutedEvent StopProgressEvent = EventManager.RegisterRoutedEvent("StopProgress", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(SearchPanel));

        private Point startPoint;
        private bool isDragging;
        private bool supportsDragDrop;

        internal ColorfulViewModel ViewModel
        {
            get { return (ColorfulViewModel)DataContext; }
        }

        public event RoutedEventHandler StartProgress
        {
            add { AddHandler(StartProgressEvent, value); }
            remove { RemoveHandler(StartProgressEvent, value); }
        }

        public event RoutedEventHandler StopProgress
        {
            add { AddHandler(StopProgressEvent, value); }
            remove { RemoveHandler(StopProgressEvent, value); }
        }

        public SearchPanel()
        {            
            InitializeComponent();
            DataContext = new ColorfulViewModel();
            this.supportsDragDrop = false;
            InitializeEvents();            
        }

        public SearchPanel(ColorfulViewModel viewModel, bool supportsDragDrop)
        {            
            InitializeComponent();
            DataContext = viewModel;
            this.supportsDragDrop = supportsDragDrop;
            InitializeEvents();            
        }

        private void InitializeEvents()
        {
            Loaded += new RoutedEventHandler(OnLoaded);
            ViewModel.PropertyChanged += new PropertyChangedEventHandler(OnPropertyChanged);
            paletteListBox.CommandBindings.Add(new CommandBinding(ApplicationCommands.Copy, CopyExecuted, CopyCanExecute));
            
            if (supportsDragDrop)
            {
                paletteListBox.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(OnPreviewMouseLeftButtonDown);
                paletteListBox.PreviewMouseMove += new MouseEventHandler(OnPreviewMouseMove);
            }
            ViewModel.ExecuteSearchCommand.Execute(null);
            RaiseEvent(new RoutedEventArgs(StartProgressEvent, this));
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {                       
//            ViewModel.ExecuteSearchCommand.Execute(null);
//            RaiseEvent(new RoutedEventArgs(StartProgressEvent, this));
        }

        private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "IsBussy")
            {
                if (ViewModel.IsBussy)
                {
                    RaiseEvent(new RoutedEventArgs(StartProgressEvent, this));
                }
                else
                {
                    RaiseEvent(new RoutedEventArgs(StopProgressEvent, this));
                    if (paletteListBox.Items.Count > 0)
                        paletteListBox.ScrollIntoView(paletteListBox.Items[0]);
                }
            }
        }

        private void OnColorMouseDown(object sender, MouseEventArgs e)
        {
            if (Keyboard.Modifiers == ModifierKeys.Control)
            {
                var colorRect = (Rectangle)sender;
                var color = ((SolidColorBrush)colorRect.Fill).Color;
                Clipboard.SetText("#" + color.ToString().Substring(3, 6));
            }
        }

        private void OnPreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed && !isDragging)
            {
                Point position = e.GetPosition(null);
                if (Math.Abs(position.X - startPoint.X) > SystemParameters.MinimumHorizontalDragDistance &&
                    Math.Abs(position.Y - startPoint.Y) > SystemParameters.MinimumVerticalDragDistance &&
                    paletteListBox.SelectedItem != null)
                {
                    StartDrag(e);
                }
            }
        }

        private void OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            startPoint = e.GetPosition(null);
        }

        private void StartDrag(MouseEventArgs e)
        {
            isDragging = true;            
            DragDropEffects de = DragDrop.DoDragDrop(paletteListBox, ViewModel.CreateDragDropObject((Palette)paletteListBox.SelectedItem), DragDropEffects.Copy);
            isDragging = false;
        }

        private void CopyCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = paletteListBox.SelectedItem != null;
        }

        private void CopyExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            ViewModel.CopyToClipboardCommand.Execute(paletteListBox.SelectedItem as Palette);
        }

        private void SwitchProvider(object sender, RoutedEventArgs e)
        {
            ViewModel.SwitchProvider();
        }
    }
}